<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DeployCoding extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'deploy:coding';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Deploy code at Coding.net';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $_SERVER['VCAP_SERVICES'] = '{"mysql":[{"name":"kofj-thss","label":"mysql","tags":["mysql"],"plan":"default","credentials":{"hostname":"10.9.1.188","port":3306,"name":"cf_639924e6_6840_4cca_8ef8_1d54cadc8d2e","username":"6Phyk1e8XBt03VwN","password":"TlRrEUSp6RLMMUnc","uri":"mysql://6Phyk1e8XBt03VwN:TlRrEUSp6RLMMUnc@10.9.1.188:3306/cf_639924e6_6840_4cca_8ef8_1d54cadc8d2e?reconnect=true","jdbcUrl":"jdbc:mysql://10.9.1.188:3306/cf_639924e6_6840_4cca_8ef8_1d54cadc8d2e?user=6Phyk1e8XBt03VwN&password=TlRrEUSp6RLMMUnc"}}],"redis-2.6":[{"name":"kofj-redis","label":"redis-2.6","tags":["key-value","nosql"],"plan":"default","credentials":{"hostname":"10.9.21.212","host":"10.9.21.212","port":5350,"password":"30493ddf-25f6-46b3-a318-621bb984797a","name":"55d29519-1c7c-4a08-a26d-34b629be44fd"}}],"filesystem-1.0":[{"name":"kofj-file","label":"filesystem-1.0","tags":["filesystem","filesystem-1.0","Persistent filesystem"],"plan":"default","credentials":{"host_path":"/home/vcap/fs/51948edec10e8c8"}}]}';
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $mysql = json_decode($_SERVER['VCAP_SERVICES'])->mysql[0]->credentials;
        $config = $this->laravel['config']['database']['connections']['mysql'];

        $path = base_path('.env');

        if (file_exists($path)) {
            $content = str_replace($config['host'], $mysql->hostname, file_get_contents($path));
            $content = str_replace($config['database'], $mysql->name, $content);
            $content = str_replace($config['username'], $mysql->username, $content);
            $content = str_replace($config['password'], $mysql->password, $content);

            file_put_contents($path, $content);
        }

        $this->info("Application key set successfully.$path");

    }
}
